/**
 * Created by wangjz on 2018/11/23.
 */
import React, { Component } from 'react';
import { Card, Form, Input, Layout, Button, Row, Col, notification } from 'antd';
import '../less/index.less';
import { submit, listCfg } from '../service';
import { UserOutlined, LockOutlined, FileImageOutlined } from '@ant-design/icons';


const { Content } = Layout;
const FormItem = Form.Item;
const prefixRCodeUrl = './public/captcha.do?rnd=';


class Root extends Component {
  state = {
    bgImg: './public/img/login-1.jpg',
    rCodeUrl: prefixRCodeUrl + Math.random(),   // 验证码地址
  };

  constructor(props) {
    super(props);
    this.init();
  }

  init = async () => {
    // 获取应用系统名称和登录背景图片url
    const cfgs = await listCfg();
    cfgs.map((item) => {
      switch (item.key) {
        case 'application.title':
          this.setState({ title: item.value });
          document.title = item.value;
          break;
        case 'application.bg.img':
          this.setState({ bgImg: item.value });
          break;
      }
    });

    // 如果登录界面在iframe中打开，则跳出iframe
    if (window.self != window.top) {
      window.parent.location.replace(window.location.href);
    }
  };

  /**
   * 点击验证码图片，重新生成验证码图片
   */
  onRCode = () => {
    this.setState({ rCodeUrl: prefixRCodeUrl + Math.random() });
  };

  /**
   * 提交用户名和口令
   * @param event
   */
  onFinish = async values => {
    const res = await submit(values);
    if (res.code == 0) {
      let returnUrl = this.getQueryString('returnUrl');
      window.location.href = returnUrl == null ? './main.html' : returnUrl + (returnUrl.indexOf('?', 0) > 0 ? '&' : '?') + '_token=' + res.data;
    } else {
      notification['error']({ message: '登录消息', description: res.msg });
    }
  };

  /**
   * 根据变量名获取匹配值
   */
  getQueryString = name => {
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    let r = window.location.search.substr(1).match(reg);
    return r != null ? unescape(r[2]) : null;
  };

  render() {
    return (
      <Layout style={{ backgroundImage: 'url(' + this.state.bgImg + ')', backgroundSize: '100% 100%' }}
              className='layout'>
        <Content className='content'>
          <div className='title'>{this.state.title}</div>
          <Card bordered={false}>
            <Form onFinish={this.onFinish} className='loginForm' layout="horizontal">
              <Form.Item name='loginName' rules={[{ required: true, message: '请输入用户名！' }]}>
                <Input prefix={<UserOutlined/>} autoComplete="off" placeholder="用户名"/>
              </Form.Item>
              <Form.Item name='password' rules={[{ required: true, message: '请输入密码！' }]}>
                <Input.Password prefix={<LockOutlined/>} autoComplete="off" placeholder="密码"/>
              </Form.Item>
              <Row>
                <Col span={16}>
                  <Form.Item name='randomCode'
                             rules={[{ required: true, message: '请输入验证码!' }, { len: 4, message: '验证码长度为4' }]}>
                    <Input prefix={<FileImageOutlined/>} autoComplete="off" placeholder="验证码"/>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <img title="刷新验证码" src={this.state.rCodeUrl} onClick={this.onRCode}/>
                </Col>
              </Row>
              <FormItem>
                <Button type="primary" htmlType="submit" block>登录</Button>
              </FormItem>
            </Form>
          </Card>
        </Content>
      </Layout>
    );
  }
}

export default Root;
